<?php 
namespace Api\Controller;
class TermtimeController extends CommonController{
	
	protected $m;

	
	function _initialize() {
		parent::_initialize();
		$this->m = D('YgclTermTime');
	}
	
	//学期信息------学年
	public function get_termtime_infos(){
		$now = Date('Y-m-d',time());
		$map = array(
			'status'=>1,
			'end_time'=>array('EGT',$now),
			'type'=>1
		);
		return  $this->m->where($map)->order('end_time asc')->select();
	}
	
	//解析学年，返回学年数组
	public function get_xuenian_ids($arr){
		foreach ($arr as $a){
			$data[] = $this->get_xnid($a); 
		}
		return $data;
	}
	
	public function get_xnid($xuenian){
		$val = ltrim($xuenian,'X');
		$val = rtrim($val,'N');
		return $val;
	}
	
	/**
	 * 根据学年获取学年信息
	 * @param unknown $xuenian
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, mixed, unknown, string, object>
	 */
	public function get_termtime_info_by_xuenian($xuenian){
		$xnid = $this->get_xnid($xuenian);
		$data = $this->m->where(array('id'=>$xnid))->find();
		return $data;
	}
	
	/**
	 * 获取学期的开始时间和结束时间
	 * @param unknown $ids 学年id 数组
	 */
	public function get_term_time($ids){
		$id_arr = $this->get_xuenian_ids($ids);
		$info = $this->m->where(array('id'=>array('in',$id_arr)))->order('end_time asc')->select();
		$cur = current($info);
		$end = end($info);
		$data = array(
			'start_time'=>$cur['start_time'],
			'end_time' =>$end['end_time']
		);
		return $data;
	}
	
	
	//当前学年
	public function get_term_time_now(){
		$info = current($this->get_termtime_infos());
		return $info;
	}
	
	//next学年
	public function get_term_time_now_next(){
		$info = current($this->get_termtime_infos());
		return $info;
	}
	
	//往期学年
	public function get_term_time_past(){
		$info = $this->get_term_time_now();
		$data = $this->m->where(array('status'=>1,'type'=>1,'end_time'=>array('LT',$info['start_time'])))->order('end_time asc')->select();
		return $data;
	}
	
	//包含当前学年和往期学年
	public function get_term_time_now_and_past(){
		$info = $this->get_term_time_now();
		$data = $this->m->where(array('status'=>1,'type'=>1,'end_time'=>array('ELT',$info['end_time'])))->order('end_time desc')->select();
		return $data;
	}
	
	//获取所有学年
	public function get_term_time_all(){
		return $this->m->where(array('status'=>1))->select();
	}
	
	
	//根据要报名的学期id，获取往期学年
	public function get_term_time_past_by_tid($tid){
		$term = M('YgclTerm')->where(array('id'=>$tid))->find();
		if($term['studyyear_count'] == '1'){
			$xnid = $this->get_xnid($term['studyyear']);
			$start_time = $this->m->where(array('id'=>$xnid))->getField('start_time');
		}else{
			$arr = explode(',',$term['studyyear']);
			$xnids = array();
			foreach ($arr as $a){
				$xnids[] = $this->get_xnid($a);
			}
			$times = $this->m->where(array('id'=>array('in',$xnids)))->order('start_time asc')->getField('start_time',true);
			$start_time = $times[0];
		}
		
		$data = $this->m->where(array('status'=>1,'type'=>1,'end_time'=>array('ELT',$start_time)))->order('end_time asc')->select();
		return $data;
	}
}